package com.xiaoshuidi.cloud.module.bpm.service.memo;

import cn.hutool.core.stream.CollectorUtil;
import cn.hutool.db.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.pojo.PageParam;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import com.xiaoshuidi.cloud.framework.security.core.LoginUser;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.bpm.controller.admin.memo.vo.BpmMemoPageVO;
import com.xiaoshuidi.cloud.module.bpm.controller.admin.memo.vo.BpmMemoVO;
import com.xiaoshuidi.cloud.module.bpm.dal.dataobject.memo.BpmMemoDO;
import com.xiaoshuidi.cloud.module.bpm.dal.mysql.memo.BpmMemoMapper;
import com.xiaoshuidi.cloud.module.system.api.user.AdminUserApi;
import com.xiaoshuidi.cloud.module.system.api.user.dto.AdminUserRespDTO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;

@Service
@Validated
public class BpmMemoServiceImpl implements BpmMemoService{

    @Resource
    private BpmMemoMapper bpmMemoMapper;
    @Resource
    private AdminUserApi adminUserApi;

    @Override
    public CommonResult<String> createMemo(BpmMemoVO bpmAddMemoVO) {
        BpmMemoDO bpmMemoDO=new BpmMemoDO();
        bpmMemoDO.setExecutor(bpmAddMemoVO.getExecutor());
        bpmMemoDO.setExecutorName(bpmAddMemoVO.getExecutorName());
        bpmMemoDO.setContent(bpmAddMemoVO.getContent());
        bpmMemoDO.setToDoTime(bpmAddMemoVO.getToDoTime());
        bpmMemoDO.setStatus("1");
        bpmMemoMapper.insert(bpmMemoDO);
        return CommonResult.success("新增成功");
    }

    @Override
    public CommonResult<String> updateMemo(BpmMemoVO bpmAddMemoVO) {
        QueryWrapper<BpmMemoDO> qw =new QueryWrapper<>();
        qw.eq("id",bpmAddMemoVO.getId());
        BpmMemoDO bpmMemoDO = bpmMemoMapper.selectOne(qw);
        bpmMemoDO.setToDoTime(bpmAddMemoVO.getToDoTime());
        bpmMemoDO.setContent(bpmAddMemoVO.getContent());
        bpmMemoDO.setExecutor(bpmAddMemoVO.getExecutor());
        bpmMemoDO.setExecutorName(bpmAddMemoVO.getExecutorName());
        bpmMemoDO.setUpdater(Objects.requireNonNull(getLoginUser()).getId().toString());
        bpmMemoDO.setUpdateTime(LocalDateTime.now());
        bpmMemoMapper.updateById(bpmMemoDO);
        return CommonResult.success("修改成功");
    }

    @Override
    public CommonResult<String> completeMemo(BpmMemoVO bpmAddMemoVO) {
        QueryWrapper<BpmMemoDO> qw =new QueryWrapper<>();
        qw.eq("id",bpmAddMemoVO.getId());
        BpmMemoDO bpmMemoDO = bpmMemoMapper.selectOne(qw);
        bpmMemoDO.setStatus(bpmAddMemoVO.getStatus());
        bpmMemoDO.setExecutor(bpmAddMemoVO.getExecutor());
        bpmMemoDO.setExecutorName(bpmAddMemoVO.getExecutorName());
        bpmMemoDO.setCompleteTime(new Date());
        bpmMemoDO.setUpdater(Objects.requireNonNull(getLoginUser()).getId().toString());
        bpmMemoDO.setUpdateTime(LocalDateTime.now());
        bpmMemoMapper.updateById(bpmMemoDO);
        return CommonResult.success("已完成");
    }

    @Override
    public List<BpmMemoDO> getMemoList(BpmMemoVO bpmAddMemoVO) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        QueryWrapper<BpmMemoDO> qw =new QueryWrapper<>();
        qw.eq("to_do_time",bpmAddMemoVO.getToDoTime()).eq("creator",loginUserId);
        List<BpmMemoDO> list = bpmMemoMapper.selectList(qw);
        List<BpmMemoDO> sortedList = list.stream()
                .sorted(Comparator.comparing(BpmMemoDO::getStatus, Comparator.comparingInt(Integer::parseInt))
                        .thenComparing(BpmMemoDO::getCreateTime, Comparator.reverseOrder()))
                .collect(Collectors.toList());
        return sortedList;
    }

    @Override
    public BpmMemoDO getMemoById(BpmMemoVO bpmAddMemoVO) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        QueryWrapper<BpmMemoDO> qw =new QueryWrapper<>();
        qw.eq("id",bpmAddMemoVO.getId()).eq("creator",loginUserId);
        BpmMemoDO bpmMemoDO = bpmMemoMapper.selectOne(qw);
        return bpmMemoDO;
    }

    @Override
    public List<Date> getMemoDate() {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        QueryWrapper<BpmMemoDO> qw =new QueryWrapper<>();
        qw.eq("creator",loginUserId);
        List<BpmMemoDO> list = bpmMemoMapper.selectList(qw);
        List<Date> dateList =new ArrayList<>();
        for (BpmMemoDO bpmMemoDO : list) {
            Date toDoTime = bpmMemoDO.getToDoTime();
            dateList.add(toDoTime);
        }
        return dateList.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public Integer getMemoNum(BpmMemoVO bpmAddMemoVO) {
        Date toDoTime = bpmAddMemoVO.getToDoTime();
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        QueryWrapper<BpmMemoDO> qw =new QueryWrapper<>();
        qw.eq("creator",loginUserId).eq("status","1").eq("to_do_time",toDoTime);
        List<BpmMemoDO> list = bpmMemoMapper.selectList(qw);
        return list.size();
    }

    @Override
    public PageResult<BpmMemoDO> getMemoPageList(BpmMemoPageVO bpmMemoPageVO) {
        LoginUser loginUser = getLoginUser();
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        //if (Objects.nonNull(loginUser) && StringUtils.isNoneEmpty(loginUser.getNickname()) ){
        if (Objects.nonNull(userId)){
            PageParam page = new PageParam();
            page.setPageNo(bpmMemoPageVO.getPageNo());
            page.setPageSize(bpmMemoPageVO.getPageSize());
            if (StringUtils.isBlank(bpmMemoPageVO.getStatus())){
                bpmMemoPageVO.setStatus("1");
            }
            //查询出执行人是自己的和执行人是所有人的记录
            LambdaQueryWrapper<BpmMemoDO> qw = new LambdaQueryWrapper<>();
            qw.in(BpmMemoDO::getExecutor,Arrays.asList(userId,"all"))
                    .eq(BpmMemoDO::getStatus,bpmMemoPageVO.getStatus())
                    .like(StringUtils.isNotBlank(bpmMemoPageVO.getContent()),BpmMemoDO::getContent,bpmMemoPageVO.getContent())
                    .orderByDesc(BpmMemoDO::getCreateTime);
            PageResult<BpmMemoDO> bpmMemoDOPageResult = bpmMemoMapper.selectPage(page, qw);
            List<BpmMemoDO> list = bpmMemoDOPageResult.getList();
            //转换修改人名称
            List<Long> ids = list.stream().map(m -> Long.valueOf(m.getUpdater())).collect(Collectors.toList());
            CommonResult<List<AdminUserRespDTO>> users = adminUserApi.getUsers(ids);
            if (CollectionUtils.isNotEmpty(users.getData())){
                Map<Long, String> collect = users.getData().stream().collect(Collectors.toMap(AdminUserRespDTO::getId, AdminUserRespDTO::getNickname));
                list.forEach(v->{
                    /*if (StringUtils.isNotEmpty(v.getExecutor())){
                        if ("all".equals(v.getExecutor())){
                            v.setExecutor("所有人");
                        }else {
                            v.setExecutor(loginUser.getNickname());
                        }
                    }*/
                    v.setCreator(collect.get(Long.valueOf(v.getCreator())));
                    v.setUpdater(collect.get(Long.valueOf(v.getUpdater())));
                });
            }

            return bpmMemoDOPageResult;
        }
        return null;
    }

    @Override
    public Long getMemoCount(Long userId) {
        LambdaQueryWrapper<BpmMemoDO> qw = new LambdaQueryWrapper<>();
        qw.eq(BpmMemoDO::getStatus,"1")
                .in(BpmMemoDO::getExecutor,Arrays.asList(userId,"all"));
        return bpmMemoMapper.selectCount(qw);
    }
}
